<template>
	<!-- 一级场景 -->
	<el-card class="card" v-loading="loading">
		<template #header>
			<div class="ml-5 flex items-center">
				<HyTitle title="一级场景" />
			</div>
		</template>
		<el-form
			ref="formRef"
			:class="formType === 'view' ? 'no-style' : null"
			:model="form"
			label-width="120"
			:disabled="formType === 'view' ? true : false"
		>
			<el-collapse v-model="firstActiveName">
				<el-collapse-item v-for="(firstItem, index) in form.sceneOneLevelList" :key="firstItem.firstId" :name="index">
					<template #title>
						<el-tag size="large" type="primary">{{ `一级场景${index + 1}` }}</el-tag>
						<el-icon
							v-if="props.operateType === 'add' || props.operateType === 'edit'"
							@click.stop="firstAdd"
							size="20"
							class="ml-3 cursor-pointer"
							color="#007fff"
							><CirclePlus
						/></el-icon>
						<el-icon
							@click.stop="firstRemove(firstItem.firstId)"
							v-if="(index !== 0 && props.operateType === 'add') || props.operateType === 'edit'"
							class="cursor-pointer ml-5"
							size="20"
							color="red"
							><CircleClose
						/></el-icon>
					</template>
					<el-form-item
						:prop="`sceneOneLevelList.${index}.sceneOneLevelName`"
						:rules="[{ required: true, message: '请输入一级场景名称' }]"
						label="一级场景名称"
					>
						<el-input
							placeholder="请输入一级场景名称"
							show-word-limit
							:rows="4"
							maxlength="2000"
							type="textarea"
							v-model="firstItem.sceneOneLevelName"
						/>
					</el-form-item>
					<!-- 二级场景 -->
					<el-card class="card mb-5">
						<template #header>
							<div class="ml-5 flex items-center">
								<HyTitle title="二级场景" />
							</div>
						</template>
						<el-collapse v-model="secondActiveName">
							<el-collapse-item v-for="(secondItem, s_index) in firstItem.sceneTwoLevelList" :key="secondItem.secondId" :name="s_index">
								<template #title>
									<el-tag size="large" type="primary">{{ `二级场景${s_index + 1}` }}</el-tag>
									<el-icon
										v-if="props.operateType === 'add' || props.operateType === 'edit'"
										@click.stop="secondAdd(firstItem.firstId)"
										size="20"
										class="ml-3 cursor-pointer"
										color="#007fff"
										><CirclePlus
									/></el-icon>
									<el-icon
										@click.stop="secondRemove(firstItem.firstId, secondItem.secondId)"
										v-if="(s_index !== 0 && props.operateType === 'add') || props.operateType === 'edit'"
										class="cursor-pointer ml-5"
										size="20"
										color="red"
										><CircleClose
									/></el-icon>
								</template>
								<el-form-item
									:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.sceneTwoLevelName`"
									:rules="[{ required: true, message: '请输入二级场景名称' }]"
									label="二级场景名称"
								>
									<el-input
										placeholder="请输入二级场景名称"
										show-word-limit
										:rows="4"
										maxlength="2000"
										type="textarea"
										v-model="secondItem.sceneTwoLevelName"
									/>
								</el-form-item>
								<el-form-item
									:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.presetFunction`"
									:rules="[{ required: true, message: '请输入预设功能' }]"
									label="预设功能"
								>
									<el-input
										placeholder="请输入预设功能"
										show-word-limit
										:rows="4"
										maxlength="2000"
										type="textarea"
										v-model="secondItem.presetFunction"
									/>
								</el-form-item>
								<el-form-item
									:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.dataSources`"
									:rules="[{ required: true, message: '请选择数据来源' }]"
									label="数据来源"
								>
									<el-select
										placeholder="请选择数据来源"
										@change="(value:any)=>dataSourcesChange(value,firstItem.firstId,secondItem.secondId)"
										multiple
										v-model="secondItem.dataSources"
									>
										<el-option v-for="(option, index) in data_sources" :label="option.label" :value="option.value" :key="index" />
									</el-select>
								</el-form-item>
								<el-form-item
									:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.dataResourceName`"
									v-if="secondItem.dataSources.includes('1')"
									:rules="[{ required: true, message: '请输入资源名称' }]"
									label="资源名称"
								>
									<el-input
										:rows="4"
										maxlength="2000"
										type="textarea"
										placeholder="请简要描述开展该二级场景业务需要采集的数据资源名称"
										v-model="secondItem.dataResourceName"
									/>
								</el-form-item>
								<!-- 系统对接 -->
								<el-card class="card" v-if="secondItem.dataSources.includes('2')">
									<template #header>
										<div class="ml-5 flex items-center">
											<HyTitle title="系统对接" />
										</div>
									</template>
									<div class="mb-5" v-for="(sourceItem, r_index) in secondItem.sceneSystemDockingList" :key="sourceItem.sourceId">
										<div class="flex items-center mb-5">
											<el-tag size="large" type="primary">{{ `系统对接${r_index + 1}` }}</el-tag>
											<el-icon
												@click="sourceAdd(firstItem.firstId, secondItem.secondId, sourceItem.sourceId)"
												size="20"
												class="ml-3 cursor-pointer"
												color="#007fff"
												v-if="props.operateType === 'add' || props.operateType === 'edit'"
												><CirclePlus
											/></el-icon>
											<el-icon
												@click="sourceRemove(firstItem.firstId, secondItem.secondId, sourceItem.sourceId)"
												v-if="(r_index !== 0 && props.operateType === 'add') || props.operateType === 'edit'"
												class="cursor-pointer ml-5"
												size="20"
												color="red"
												><CircleClose
											/></el-icon>
										</div>
										<div>
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.sceneSystemDockingList.${r_index}.dataResourceName`"
												:rules="[{ required: true, message: '请输入资源名称' }]"
												label="资源名称"
											>
												<el-input
													placeholder="请输入资源名称"
													show-word-limit
													:rows="4"
													maxlength="2000"
													type="textarea"
													v-model="sourceItem.dataResourceName"
												/>
											</el-form-item>
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.sceneSystemDockingList.${r_index}.systemName`"
												:rules="[{ required: true, message: '请输入系统名称' }]"
												label="系统名称"
											>
												<el-input
													placeholder="请输入系统名称"
													show-word-limit
													:rows="4"
													maxlength="2000"
													type="textarea"
													v-model="sourceItem.systemName"
												/>
											</el-form-item>
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.sceneSystemDockingList.${r_index}.managerUnit`"
												:rules="[{ required: true, message: '请输入主营单位' }]"
												label="主营单位"
											>
												<el-input
													placeholder="请输入主营单位"
													show-word-limit
													:rows="4"
													maxlength="2000"
													type="textarea"
													v-model="sourceItem.managerUnit"
												/>
											</el-form-item>
										</div>
									</div>
								</el-card>
								<el-alert style="background-color: var(--el-color-primary); color: #fff; margin: 10px 0" title="用户体系" :closable="false" />
								<el-form-item
									:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.serviceClient`"
									label="服务端（业务申请方）"
									label-width="180"
									:rules="[{ required: true, message: '请输入服务端（业务申请方' }]"
								>
									<el-input
										type="textarea"
										maxlength="2000"
										show-word-limit
										placeholder="请输入使用该应用进行业务申请的对象"
										v-model="secondItem.serviceClient"
									/>
								</el-form-item>
								<!-- 管理端 -->
								<el-card class="card mb-5">
									<template #header>
										<div class="ml-5 flex items-center">
											<HyTitle title="管理端（业务受理方）" />
										</div>
									</template>
									<div v-for="(manageItem, m_index) in secondItem.businessAcceptancePartyList" :key="manageItem.manageId">
										<div class="flex items-center">
											<el-tag size="large" type="primary">{{ `管理端（业务受理方）${m_index + 1}` }}</el-tag>
											<el-icon
												@click="manageAdd(firstItem.firstId, secondItem.secondId, manageItem.menageId)"
												size="20"
												class="ml-3 cursor-pointer"
												color="#007fff"
												v-if="props.operateType === 'add' || props.operateType === 'edit'"
												><CirclePlus
											/></el-icon>
											<el-icon
												v-if="(m_index !== 0 && props.operateType === 'add') || props.operateType === 'edit'"
												@click="manageRemove(firstItem.firstId, secondItem.secondId, manageItem.menageId)"
												class="cursor-pointer ml-5"
												size="20"
												color="red"
												><CircleClose
											/></el-icon>
										</div>
										<div class="my-5">
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.businessAcceptancePartyList.${m_index}.involveLevel`"
												:rules="[{ required: true, message: '请选择层级' }]"
												label="层级"
											>
												<el-select placeholder="请选择层级" v-model="manageItem.involveLevel">
													<el-option v-for="(option, index) in involve_level" :label="option.label" :value="option.value" :key="index" />
												</el-select>
											</el-form-item>
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.businessAcceptancePartyList.${m_index}.involveDepart`"
												:rules="[{ required: true, message: '请输入部门' }]"
												label="部门"
											>
												<el-input
													maxlength="2000"
													show-word-limit
													placeholder="请输入涉及部门，不同部门用“、”间隔。"
													v-model="manageItem.involveDepart"
												/>
											</el-form-item>
											<el-form-item
												:prop="`sceneOneLevelList.${index}.sceneTwoLevelList.${s_index}.businessAcceptancePartyList.${m_index}.responsibilitiesFulfilled`"
												:rules="[{ required: true, message: '请输入职责' }]"
												label="职责"
											>
												<el-input
													placeholder="请输入职责"
													maxlength="2000"
													show-word-limit
													:rows="4"
													type="textarea"
													v-model="manageItem.responsibilitiesFulfilled"
												/>
											</el-form-item>
										</div>
									</div>
								</el-card>
							</el-collapse-item>
						</el-collapse>
					</el-card>
					<el-form-item
						:prop="`sceneOneLevelList.${index}.dataSharing`"
						:rules="[{ required: true, message: '请输入多跨数据共享' }]"
						label="多跨数据共享"
					>
						<el-input placeholder="请输入多跨数据共享" show-word-limit :rows="4" maxlength="2000" type="textarea" v-model="firstItem.dataSharing" />
					</el-form-item>
					<el-form-item
						:prop="`sceneOneLevelList.${index}.businessCollaboration`"
						:rules="[{ required: true, message: '请输入多跨业务协同' }]"
						label="多跨业务协同"
					>
						<el-input
							placeholder="请输入多跨业务协同"
							show-word-limit
							:rows="4"
							maxlength="2000"
							type="textarea"
							v-model="firstItem.businessCollaboration"
						/>
					</el-form-item>
				</el-collapse-item>
			</el-collapse>
		</el-form>
	</el-card>
</template>
<script setup lang="ts">
import HyTitle from '/@/components/HyTitle/index.vue';
const { firstDefalut, secondDefault, sourceDefault, menageDefault } = defaultValue();
import { defaultValue, setKeyValue } from '../../../../utils/default';
import { useDict } from '/@/hooks/dict';
import { getUUId } from '/@/utils/hyFunc';

const formType: any = inject('formType', 'submit');
const { data_sources, involve_level } = useDict('data_sources', 'involve_level');
const form: any = ref({
	sceneOneLevelList: [],
});

//系统对接新增
const sourceAdd = (firstId: string, secondId: string, sourceId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			f_item.sceneTwoLevelList.forEach((s_item: any) => {
				if (s_item.secondId === secondId) {
					s_item.sceneSystemDockingList.forEach((m_item: any) => {
						if (m_item.sourceId === sourceId) {
							s_item.sceneSystemDockingList.push({
								sourceId: getUUId(),
								...sourceDefault,
							});
						}
					});
				}
			});
		}
	});
};
//系统对接删除
const sourceRemove = (firstId: string, secondId: string, sourceId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			f_item.sceneTwoLevelList.forEach((s_item: any) => {
				if (s_item.secondId === secondId) {
					s_item.sceneSystemDockingList.forEach((m_item: any) => {
						if (m_item.sourceId === sourceId) {
							s_item.sceneSystemDockingList = s_item.sceneSystemDockingList.filter((item: any) => item.sourceId !== sourceId);
						}
					});
				}
			});
		}
	});
};
//管理端新增
const manageAdd = (firstId: string, secondId: string, menageId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			f_item.sceneTwoLevelList.forEach((s_item: any) => {
				if (s_item.secondId === secondId) {
					s_item.businessAcceptancePartyList.forEach((m_item: any) => {
						if (m_item.menageId === menageId) {
							s_item.businessAcceptancePartyList.push({
								menageId: getUUId(),
								...menageDefault,
							});
						}
					});
				}
			});
		}
	});
};
//管理端删除
const manageRemove = (firstId: string, secondId: string, menageId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			f_item.sceneTwoLevelList.forEach((s_item: any) => {
				if (s_item.secondId === secondId) {
					s_item.businessAcceptancePartyList.forEach((m_item: any) => {
						if (m_item.menageId === menageId) {
							s_item.businessAcceptancePartyList = s_item.businessAcceptancePartyList.filter((item: any) => item.menageId !== menageId);
						}
					});
				}
			});
		}
	});
};
//二级场景新增
const secondActiveName = ref([0]);
const secondAdd = (firstId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			const secondId = getUUId();
			f_item.sceneTwoLevelList.push({
				secondId,
				...secondDefault,
				sceneSystemDockingList: [
					{
						sourceId: getUUId(),
						...sourceDefault,
					},
				],
				businessAcceptancePartyList: [{ menageId: getUUId(), ...menageDefault }],
			});
		}
	});
};
//二级场景删除
const secondRemove = (firstId: string, secondId: string) => {
	setLoading();
	form.value.sceneOneLevelList.forEach((f_item: any) => {
		if (f_item.firstId === firstId) {
			f_item.sceneTwoLevelList = f_item.sceneTwoLevelList.filter((item: any) => item.secondId !== secondId);
		}
	});
};
//一级场景新增
const firstActiveName: any = ref([0]);
const firstAdd = () => {
	setLoading();
	const firstId: string = getUUId();
	const secondId: string = getUUId();
	form.value.sceneOneLevelList.push({
		firstId,
		...firstDefalut,
		sceneTwoLevelList: [
			{
				secondId,
				...secondDefault,
				sceneSystemDockingList: [
					{
						sourceId: getUUId(),
						...sourceDefault,
					},
				],
				businessAcceptancePartyList: [{ menageId: getUUId(), ...menageDefault }],
			},
		],
	});
};
//一级场景删除
const firstRemove = (firstId: string) => {
	setLoading();
	form.value.sceneOneLevelList = form.value.sceneOneLevelList.filter((item: any) => item.firstId !== firstId);
};

//设置假loading
const loading = ref(false);
const setLoading = () => {
	loading.value = true;
	setTimeout(() => {
		loading.value = false;
	}, 300);
};
//数据来源选择
const dataSourcesChange = (selectArray: any, firstId: string, secondId: string) => {
	//系统对接
	if (selectArray.includes('2')) {
		form.value.sceneOneLevelList.forEach((f_item: any) => {
			if (f_item.firstId === firstId) {
				f_item.sceneTwoLevelList.forEach((s_item: any) => {
					if (s_item.secondId === secondId) {
						s_item.sceneSystemDockingList = [
							{
								sourceId: getUUId(),
								...sourceDefault,
							},
						];
					}
				});
			}
		});
	} else {
		form.value.sceneOneLevelList.forEach((f_item: any) => {
			if (f_item.firstId === firstId) {
				f_item.sceneTwoLevelList.forEach((s_item: any) => {
					if (s_item.secondId === secondId) {
						delete s_item.sceneSystemDockingList;
					}
				});
			}
		});
	}
};
const props: any = defineProps({
	sceneOneLevelData: {
		type: Array,
		default: () => {
			return [];
		},
	},
	operateType: {
		type: String,
		default: '',
	},
});

//回显数据
const echoData = (data: any) => {
	const setIdForm = data.map((f_item: any) => {
		const firstId: string = getUUId();
		const secondId: string = getUUId();
		const secondArray = f_item.sceneTwoLevelList || [];
		return {
			firstId,
			...setKeyValue(firstDefalut, f_item),
			sceneTwoLevelList: secondArray.map((s_item: any) => {
				const sourceArray = s_item.sceneSystemDockingList || [];
				const manageArray = s_item.businessAcceptancePartyList || [];
				//dataSources字符串转为数组
				const dataSourcesArray = s_item?.dataSources ? s_item.dataSources.split(',') : [];
				dataSourcesChange(dataSourcesArray, firstId, secondId);
				return {
					...setKeyValue(secondDefault, { ...s_item, dataSources: dataSourcesArray }),
					secondId,
					sceneSystemDockingList: sourceArray.map((r_item: any) => {
						return {
							sourceId: getUUId(),
							...setKeyValue(sourceDefault, r_item),
						};
					}),
					businessAcceptancePartyList: manageArray.map((b_item: any) => {
						return {
							menageId: getUUId(),
							...setKeyValue(menageDefault, b_item),
						};
					}),
				};
			}),
		};
	});
	form.value.sceneOneLevelList = setIdForm;
};
watch(
	() => props,
	(nv1: any) => {
		const { sceneOneLevelData } = nv1;
		//view的时候，展示数据
		if (formType.value === 'view') {
			nextTick(() => {
				if (sceneOneLevelData && sceneOneLevelData.length > 0) {
					echoData(sceneOneLevelData);
				}
			});
		} else {
			nextTick(() => {
				if (sceneOneLevelData && sceneOneLevelData.length > 0) {
					echoData(sceneOneLevelData);
				} else {
					firstAdd();
				}
			});
		}
	},
	{ deep: true, immediate: true }
);
const formRef = ref();
const check = () => {
	return formRef.value.validate((valid: boolean) => {
		if (!valid) {
			setTimeout(() => {
				const el = document.querySelectorAll('.el-form-item__error')[0];
				el.scrollIntoView({ block: 'center', behavior: 'smooth' });
			}, 100);
		}
		return valid;
	});
};
defineExpose({ form, check });
</script>
<style scoped lang="scss">
.card {
	:deep(.el-card__header) {
		padding: 5px 0;
	}
	:deep(.el-card__body) {
		padding: 10 30px;
	}
}
.view-form {
	.el-form-item {
		display: flex;
		flex: 1;
		:deep(.el-form-item__content) {
			flex: 1;
			display: flex;
			align-items: center;
			margin-left: 0 !important;
		}
	}
}
</style>
